﻿using System;
using System.IO;
using System.IO.IsolatedStorage;
using System.Collections.Generic;
using System.Diagnostics;
using Redbrick.Silverlight.Serialization;

namespace DeenGames.Utils
{
    ///<summary>
     /// An Isolated Storage-based persistent storage provider.
     ///</summary>
    class IsolatedStorageProvider : IPersistentStorageProvider
    {
        // Used to access the actual storage
        private static IsolatedStorageFile isf;

        public IsolatedStorageProvider()
        {
            // Throws an exception if Isolated Storage is disabled
            isf = IsolatedStorageFile.GetUserStoreForApplication();
        }

        #region IPersistentStorageProvider Members

        public string Store<_type>(string key, _type value)
        {
            string newKey = PersistentStorageHelper.Hash(key) + ".dat";
            using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(newKey , System.IO.FileMode.Create, isf))
            {
                SilverlightSerializer.Serialize(value, stream);
                //using (TextWriter writer = new StreamWriter(stream, System.Text.Encoding.UTF8))
                //{

                //    try
                //    {
                //        string serialized = PersistentStorageHelper.Serialize(value);
                //        string encrypted = PersistentStorageHelper.Encrypt(serialized);
                //        writer.WriteLine(encrypted);
                //    }
                //    catch (IsolatedStorageException e)
                //    {
                //        throw new InvalidOperationException(string.Format("Could not save {0} = {1} because there's no space left in Isolated Storage; nested exception is {2}.", key, value, e));
                //    }

                //    writer.Flush();
                //    stream.Flush();
                //}
            }
            return newKey;
        }

        public _type Retrieve<_type>(string key)
        {

            try
            {
					string filename = PersistentStorageHelper.Hash(key) + ".dat";
					using (var store = IsolatedStorageFile.GetUserStoreForApplication())
					{

						if (store.FileExists(filename))
						{
							using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(filename, System.IO.FileMode.Open, isf))
							{
								return SilverlightSerializer.Deserialize<_type>(stream);
							}
						}
					}
            }
            catch (IsolatedStorageException e)
            {
                Debug.WriteLine("Exception: " + e);
            }
            return default(_type);
        }

        public void Remove(string key)
        {
            string path = PersistentStorageHelper.Hash(key) + ".dat";
            try
            {
                isf.DeleteFile(path);
            }
            catch (IsolatedStorageException e)
            {
                Debug.WriteLine("Exception: " + e);
            }
        }

        public void Clear()
        {
            isf.Remove();
        }

        #endregion

        public IEnumerable<string> Keys
        {
            get
            {
                IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication();
                string[] names = isf.GetFileNames();
                foreach (string key in names)
                    yield return key;
            }
        }
    }
}
